<script setup>
import { ref } from 'vue';
import request from '@/utils/request'   
import { Notify } from 'vant';
import 'vant/es/notify/style';
import { useRouter } from 'vue-router';

const router =useRouter()

const onBackLogin = () => history.back();

const email = ref('')
const username = ref('');
const password = ref('');
const checked = ref('')

// 提交表单
const onSubmit =async (values) => {
    const {data} = await request.post('/user/reg',{  
        username:username.value,
        password:password.value,
        email:email.value
    })
    if (data.code === 200) {
        Notify({ type: 'success', message: '注册成功' })
        // 清空输入框
        username.value=''
        password.value=''
        email.value=''
        checked.value=''

        // 跳到登录页面
        router.push('/login')
    } else if (data.code === 400) {
        Notify({ type: 'danger', message: '注册失败' })
    }
    console.log('reg',data)
};

// 校验确认密码
const validator = (val) => { 
    if(val!== password.value){
        Notify({ type: 'danger', message: '两次密码不一致' })
    }
}

// 校验用户名是否被占用 ---校验函数可以返回 Promise，实现异步校验
const asyncValidator = function(val){
    new Promise((resolve, reject) => {
        request.get('/user/check?username=' +val).then(function ({ data }) {
            console.log('check',data)
            if (data.code === 200) {
                resolve()
            } else if (data.code === 400) {
                Notify({ type: 'danger', message: '用户名已被注册' })
            }
        })
    })
}

</script>
<template>
    <van-nav-bar title="注册" left-arrow @click-left="onBackLogin" />
    <main>
        <van-form @submit="onSubmit">
            <van-cell-group inset>
                <van-field v-model="email" name="email" label="手机/邮箱" placeholder="手机/邮箱"
                    :rules="[{ required: true, message: '邮箱' }]" />
                <van-field v-model="username" name="username" label="昵称" placeholder="昵称"
                    :rules="[{ required: true, message: '昵称', validator: asyncValidator }]" />
                <van-field v-model="password" type="password" name="password" label="密码" placeholder="密码"
                    :rules="[{ required: true, message: '请填写密码' }]" />
                <van-field v-model="checked" type="password" name="apassword" label="确认密码" placeholder="确认密码"
                    :rules="[{ required: true, message: '请再一次输入密码', validator }]" />
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button round block type="primary" native-type="submit">
                    注册
                </van-button>
            </div>
        </van-form>
    </main>
</template>